package com.foreverwin.jzymes.eap.Listener;

import com.alibaba.fastjson.JSONObject;
import com.foreverwin.jzymes.common.service.ICustomFieldsAdviceService;
import com.foreverwin.jzymes.common.service.IResourceAdviceService;
import com.foreverwin.jzymes.framework.annotation.MessageLog;
import com.foreverwin.jzymes.framework.event.AppEvent;
import org.apache.activemq.command.ActiveMQTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Component;

@Component
public class ResourceStatusListener {

    Logger logger = LoggerFactory.getLogger( ResourceStatusListener.class );

    @Autowired
    IResourceAdviceService resourceAdviceService;
    @Autowired
    ICustomFieldsAdviceService customFieldsAdviceService;
    @Autowired
    JmsMessagingTemplate jmsTemplate;

    @JmsListener( destination = "MES_RESOURCE_STATUS_INFRA" )
    @MessageLog
    public void resourceStatusFromQueue( String resourceTimeLogJson ) {
        logger.info( "接收到设备状态信息: " + resourceTimeLogJson );
        try{
            JSONObject resourceTimeLogMap = JSONObject.parseObject( resourceTimeLogJson );
            String site = (String)resourceTimeLogMap.get( "SITE" );
            String resrce = (String)resourceTimeLogMap.get( "RESRCE" );
            String status = (String)resourceTimeLogMap.get( "STATUS" );
            //Date sendTime = DateUtil.parse( (String) resourceTimeLogMap.get( "SEND_TIME" ) );

            String currentStatus = resourceAdviceService.findResourceStatus( site, resrce );
            if( "REPAIR".equals( currentStatus ) || "TPM".equals( currentStatus )  ){
                return;
            }

            /**cnc设备要遵循设备状态转换规则，其他设备状态以上传状态为准*/
            if( resourceAdviceService.isCNC( site, resrce ) ){
                resourceAdviceService.changeResourceStatus( site, resrce, status );
            }else{
                resourceAdviceService.updateResourceStatus( site, resrce, status );
            }

            /**发送设备状态变化到页面*/
            JSONObject eventData = new JSONObject();
            eventData.put( "SITE", site );
            eventData.put( "RESRCE", resrce );
            eventData.put( "STATUS", status );
            AppEvent<JSONObject> appEvent = new AppEvent<>( this );
            appEvent.setName( "RESOURCE_STATUS_CHANGE" );
            appEvent.setData( eventData );
            ActiveMQTopic topic = new ActiveMQTopic( "MES_APP_EVENT_INFRA" );
            jmsTemplate.convertAndSend( topic, appEvent );

            logger.info( "设备状态信息处理完成: " + resourceTimeLogJson );
        }catch ( Exception e ){
            logger.error( "设备状态信息处理失败: " + e.getMessage() + "，设备状态信息: " + resourceTimeLogJson );
            throw e;
        }
    }
}
